package cn.timelost.hr.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;


import cn.timelost.hr.config.AliOssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import org.aspectj.weaver.patterns.PerObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.upyun.RestManager;
import com.upyun.UpException;

import cn.hutool.core.util.StrUtil;
import cn.timelost.hr.enums.ResultEnum;
import cn.timelost.hr.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;

import static cn.timelost.hr.enums.ResultEnum.UPLOAD_FAIL;


@RestController
@Slf4j
@RequestMapping("/image")
public class ImageController {
    @Autowired
    private AliOssConfig aliOssConfig;


    @PostMapping("/upload")
    public ResultVo upload(@RequestParam("file") MultipartFile multipartFile) throws IOException, UpException {

/*
        if (StrUtil.isBlank(upYunConfig.getBucketName()) || StrUtil.isBlank(upYunConfig.getUsername()) ||
                StrUtil.isBlank(upYunConfig.getPassword()) || StrUtil.isBlank(upYunConfig.getImageHost())) {
            return ResultVo.fail(ResultEnum.UPLOAD_NOT_ENABLE);
        }
        RestManager manager = new RestManager(upYunConfig.getBucketName(), upYunConfig.getUsername(),
                upYunConfig.getPassword());
        String fileName = "/ehr/" + genUniqueKey() + ".jpg";
        Response response = manager.writeFile(fileName, multipartFile.getInputStream(), (Map) null);
        String imgUrl = upYunConfig.getImageHost() + fileName;
        if (response.isSuccessful()) {
            log.info(imgUrl);
            return ResultVo.success(imgUrl);
        }
        return ResultVo.fail(ResultEnum.UPLOAD_FAIL);

*/

        //将图片放在本地的操作
   /*     String originalFilename = multipartFile.getOriginalFilename();
        // 生成新的文件名
        String parent = "/Users/liuyukun/工作空间/IdeaProjects/springboot-ehr/img";
        String fileName = genUniqueKey() + ".jpg";
        multipartFile.transferTo(new File(parent + fileName));
        return ResultVo.success("http://localhost:8080/img/" + fileName);*/


        //阿里oss文件上传
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        String OSS_ACCESS_KEY_ID = "LTAI5tEssYRC7aMVswbStvka";
        String OSS_ACCESS_KEY_SECRET = "NDydn6HG5K8nG20VapE7Lz5DOLchXx";
        /*EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();*/
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ehr-kun";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String uniquekey = genUniqueKey();
        String objectName = "exampledir/" + uniquekey + ".jpg";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        String parent = "E:\\keseWeb\\springboot-ehr\\springboot-ehr\\img";
        String fileName = uniquekey + ".jpg";
        multipartFile.transferTo(new File(parent + fileName));
        String filePath = parent + fileName;
        // 创建OSSClient实例。
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));

            // 上传文件。
       /* try {
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            ossClient.shutdown();
            // 根据上传结果返回相应的信息
            if (result != null && result.getResponse() != null && result.getResponse().isSuccessful()) {
                String imgUrl = "https://ehr-kun.oss-cn-beijing.aliyuncs.com/" + objectName;
                return ResultVo.success(imgUrl);
            } else {
                return ResultVo.fail(ResultEnum.UPLOAD_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail(ResultEnum.UPLOAD_FAIL);
        }*/
            String imgUrl = "https://ehr-kun.oss-cn-beijing.aliyuncs.com/" + objectName;
            ossClient.putObject(putObjectRequest);
            return ResultVo.success(imgUrl);}
        catch (Exception e){
            return ResultVo.fail(UPLOAD_FAIL,"上传失败");
        }
        }



    //获取一个唯一值作为文件名上传
    public static synchronized String genUniqueKey() {
        Random random = new Random();
        Integer number = random.nextInt(900000) + 100000;
        return System.currentTimeMillis() + String.valueOf(number);
    }
}